<template>
    <div class="page login">
        <el-col :span="14"></el-col>
        <el-col :span="6">
            <el-form class="login-form">
                <h1>欢迎登录</h1>
                <el-form-item>
                    <el-input
                        type="text"
                        placeholder="请输入用户名"
                        size="large"
                        v-model.trim="username"
                        :prefix-icon="User"
                    />
                </el-form-item>
                <el-form-item>
                    <el-input
                        type="password"
                        placeholder="请输入密码"
                        size="large"
                        v-model.trim="password"
                        show-password
                        :prefix-icon="Lock"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button
                        @click="handleLogin"
                        type="primary"
                        class="btn-login"
                        size="large"
                        >登录</el-button
                    >
                </el-form-item>
                <div class="login-tips">
                    还没有账号，<router-link to="/register">去注册</router-link>
                </div>
            </el-form>
        </el-col>
    </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { User, Lock } from "@element-plus/icons-vue";
import { ref, onMounted } from "vue";
import { UserLogin } from "@/api/users";
import { GetCookie, SetCookie } from "@/utils/cookie";
const router = useRouter();
const username = ref("");
const password = ref("");

// 登录
const handleLogin = async () => {
    if (username.value === "" || password.value === "") {
        return ElMessage.error("请输入账号和密码");
    }
    const res = await UserLogin(username.value, password.value);
    if (res) {
        ElMessage.success("登录成功");
        SetCookie("userid", res.id);
        router.replace("/");
    }
};

onMounted(() => {
    const userid = GetCookie("userid");
    if (userid) {
        router.replace("/");
    }
});
</script>

<style lang="scss" scoped>
.login {
    justify-content: center;
    align-items: center;
    background-image: url("../../assets/login-bg.jpg");
    background-repeat: no-repeat;
    background-size: cover;
    .login-form {
        background-color: rgba(0, 0, 0, 0.45);
        box-sizing: border-box;
        padding: 40px 50px;
        border-radius: 6px;
        h1 {
            font-size: 30px;
            color: #fff;
            margin-bottom: 20px;
        }
        .btn-login {
            width: 100%;
        }
        .login-tips {
            color: #fff;
            text-align: center;
            a {
                color: skyblue;
            }
        }
    }
}
</style>
